import 'dart:async';

import 'package:flutter/material.dart';
import 'package:specialty_no1/modules/size.dart';

/// 倒计时样式
enum CountdownStyle {
  style1,
  style2,
}

/// 倒计时小部件
class CountdownWidget extends StatefulWidget {
  final DateTime endTime;
  final CountdownStyle style;
  const CountdownWidget({Key key, @required this.endTime, this.style = CountdownStyle.style1}) : super(key: key);
  @override
  _CountdownWidgetState createState() => _CountdownWidgetState();
}

class _CountdownWidgetState extends State<CountdownWidget> {
  String hourStr = "00";
  String minuteStr = "00";
  String secondStr = "00";
  @override
  void initState() {
    super.initState();
    Timer.periodic(Duration(seconds: 1), (timer) {
      Duration d = widget.endTime.difference(DateTime.now());
      int hour = d.inSeconds ~/ (60 * 60);
      int minute = d.inSeconds % (60 * 60) ~/ 60;
      int second = d.inSeconds % (60 * 60) % 60;
      setState(() {
        hourStr = hour < 10 ? "0" + hour.toString() : hour.toString();
        minuteStr = minute < 10 ? "0" + minute.toString() : minute.toString();
        secondStr = second < 10 ? "0" + second.toString() : second.toString();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (widget.style == CountdownStyle.style1) {
      Widget interval = Container(
        padding: EdgeInsets.only(left: 1, right: 1),
        child: Text(
          ":",
          style: TextStyle(fontSize: MySize.S(20)),
        ),
      );
      return Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _timeItem(hourStr),
            interval,
            _timeItem(minuteStr),
            interval,
            _timeItem(secondStr),
          ],
        ),
      );
    } else if (widget.style == CountdownStyle.style2) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 3, vertical: 1),
        child: Text(
          "$hourStr:$minuteStr:$secondStr",
          style: TextStyle(fontSize: MySize.S(18), color: Color(0xffF20C59)),
        ),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(5), border: Border.all(color: Color(0xffF20C59))),
      );
    } else {
      return Container();
    }
  }

  Widget _timeItem(String timeStr) {
    return Container(
      width: MySize.V(28),
      height: MySize.V(28),
      alignment: Alignment.center,
      decoration: BoxDecoration(color: Colors.black, borderRadius: BorderRadius.circular(3)),
      child: Text(
        timeStr,
        style: TextStyle(color: Colors.white, fontSize: MySize.S(20)),
      ),
    );
  }
}
